package com.sendpo.zjx.sendpo.activity;

import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jrummyapps.android.animations.Technique;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.HelpInfoDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/7/7.
 */

public class HelpthingsActivity extends AppCompatActivity implements AMap.OnMyLocationChangeListener ,AMapLocationListener{

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.index_head)
    RelativeLayout indexHead;

    @BindView(R.id.cir_icon)
    CircleImageView cirIcon;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.textcontent)
    TextView textcontent;
    @BindView(R.id.userlistitem)
    LinearLayout userlistitem;
    @BindView(R.id.uname)
    TextView uname;
    @BindView(R.id.mapview)
    MapView mapview;
  //  public List<Marker> overlayOptionses = null;
    public boolean isDestory=false;
    private AMap aMap=null;
    public     ArrayList<Marker> markers=null;
    private  String city="";
    private  String area="";
    private AmapLocationService amapLocationService;
    public boolean isFirst=true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_helpthings);
        Tools.initStatus(this, R.color.black);
        ButterKnife.bind(this);
        mapview.onCreate(savedInstanceState);
        if(aMap==null){
            aMap=mapview.getMap();
        }
        initComponent();

    }
    public AMapLocationClientOption getDefaultAmapLocationOptions(){
        AMapLocationClientOption mLocationOption=null;
        if(mLocationOption==null){
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
       //     mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷1新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return  mLocationOption;
    }
    public void initComponent() {
        final UiSettings uiSettings =  aMap.getUiSettings();
        uiSettings.setLogoBottomMargin(-50);//隐藏logo
        //开启室内地图
        aMap.showIndoorMap(true);
        //是否开启指南针
        aMap.getUiSettings().setCompassEnabled(false);
        //是否开启定位按钮
        aMap.setMyLocationEnabled(true);
        aMap.getUiSettings().setMyLocationButtonEnabled(false); //显示默认的定位按钮
        aMap.getUiSettings().setScaleControlsEnabled(true);//控制比例尺控件是否显示
        MyLocationStyle myLocationStyle= new MyLocationStyle();//初始化定位蓝点样式类;
        //  MyLocationStyle strokeColor();//设置定位蓝点精度圆圈的边框颜色的方法。
        //设置定位蓝点精度圆圈的填充颜色的方法。
        // myLocationStyle.radiusFillColor(getResources().getColor(R.color.default_theme));
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.translucent));
        myLocationStyle.strokeWidth(0.0f);
        myLocationStyle.strokeColor(getResources().getColor(R.color.translucent));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //J监听点击事件
        aMap.setOnMyLocationChangeListener(this);
        aMap.setTrafficEnabled(true);
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                    final HelpInfoDomain.DataBean  dataBean= (HelpInfoDomain.DataBean) marker.getObject();
                Technique.DROP_OUT.playOn(userlistitem);
                final CircleImageView circleImageView=userlistitem.findViewById(R.id.cir_icon);
                circleImageView.setImageResource(R.drawable.nim_avatar_default);
                Glide.with(HelpthingsActivity.this)
                        .load(dataBean.getUserAvatarpath())
                        .asBitmap()
                        .animate(R.anim.fade_in)
                        .placeholder(R.drawable.nim_avatar_default)
                        .override(300,300)
                        .centerCrop()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                              circleImageView.setImageBitmap(resource);
                            }
                        });
                  TextView uname=userlistitem.findViewById(R.id.uname);
                uname.setText(""+dataBean.getUserName());
                TextView title=userlistitem.findViewById(R.id.title);
                title.setText(""+dataBean.getHelpTitle());
                TextView price_tv=userlistitem.findViewById(R.id.price_tv);
                price_tv.setText(dataBean.getHelpMoney()+"元"+"/次");
                        userlistitem.setVisibility(View.VISIBLE);
                TextView textcontent=userlistitem.findViewById(R.id.textcontent);
                userlistitem.findViewById(R.id.userinfo_bt)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                List<User> oderuserList= Xutils.queryAll(getApplication(),User.class);
                                if(oderuserList==null||oderuserList.size()==0){
                                    Tools.redirectActivity(HelpthingsActivity.this,LoginActivity.class);
                                    return;
                                }
                                watchView(dataBean.getHelpid()+"");
                                Map<String,Object> userinfo=new HashMap<>();
                                userinfo.put("helpid",dataBean.getHelpid());
                                Tools.redirectActivity(HelpthingsActivity.this,HelpinguserinfoActivity.class,userinfo);
                                userlistitem.setVisibility(View.GONE);
                            }
                        });
                textcontent.setText(dataBean.getHelpInfo());
                userlistitem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<User> oderuserList= Xutils.queryAll(getApplication(),User.class);
                        if(oderuserList==null||oderuserList.size()==0){
                       Tools.redirectActivity(HelpthingsActivity.this,LoginActivity.class);
                            return;
                        }
                        watchView(dataBean.getHelpid()+"");
                        Map<String,Object> userinfo=new HashMap<>();
                          userinfo.put("helpid",dataBean.getHelpid());
                 Tools.redirectActivity(HelpthingsActivity.this,HelpinguserinfoActivity.class,userinfo);
                        userlistitem.setVisibility(View.GONE);

                    }
                });
                return false;
            }
        });
        //信息窗口
        amapLocationService=new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.start();

    }

    @Override
    protected void onStart() {
        super.onStart();
        query();
    }
    public void query(){
             List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList!=null&&userList.size()!=0){
                    city=userList.get(0).getUserCity();
                    area=userList.get(0).getUserArea();
                }
        if(TextUtils.isEmpty(city)){
            return;
        }
        if(TextUtils.isEmpty(area)){
            return;
        }
       Map<String,String> map=new HashMap<>();
       map.put("helpCity",""+city);
       map.put("helpArea",""+area);
        Xutils.POST(HttpUrl.userneedhelpquerylocation, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                HelpInfoDomain userMapDomain=gson.fromJson(result, HelpInfoDomain.class);
                switch (userMapDomain.getState()){
                    case HttpCode.SUCCESS:
                        if(userMapDomain.getData()!=null&&userMapDomain.getData().size()!=0){
                            if (markers!= null) {
                                for (int i = 0; i < markers.size(); i++) {
                                    Marker options = markers.get(i);
                                    options.remove();
                                }
                                markers.removeAll(markers);
                            }else{
                                markers=new ArrayList<Marker>();
                            }
                            for(int i=0;i<userMapDomain.getData().size();i++){
                                HelpInfoDomain.DataBean  dataBean=userMapDomain.getData().get(i);
                                MarkerOptions markerOptions=new MarkerOptions();
                                //是否可以拖拽定位点
                                markerOptions.draggable(false);
                                //设置好经度，纬度坐标
                                LatLng latLng=new LatLng(Double.parseDouble(dataBean.getHelpLatitude()),Double.parseDouble(dataBean.getHelpLongitude()));
                                //设置好坐标标题
                                markerOptions.title(dataBean.getUserName()+"");
                                //设置定位点的显示效果
                                markerOptions.setFlat(true);//设置marker平贴地图效果
                                markerOptions.infoWindowEnable(false);
                                markerOptions.setGps(false);
                                Marker marker=aMap.addMarker(markerOptions);
                                marker.setPosition(latLng);
                                marker.setIcon(BitmapDescriptorFactory.fromView(View.inflate(HelpthingsActivity.this, R.layout.circle_views, null)));
                                marker.setObject(dataBean);
                                markers.add(marker);
                            }
                            for(int i=0;i<markers.size();i++){
                                HelpInfoDomain.DataBean  dataBean=userMapDomain.getData().get(i);
                                final Marker marker = markers.get(i);
                                Glide.with(getApplicationContext())
                                        .load(dataBean.getUserAvatarpath())
                                        .asBitmap()
                                        .animate(R.anim.fade_in)
                                        .override(DensityUtil.dip2px(35), DensityUtil.dip2px(35))
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                View view = View.inflate(HelpthingsActivity.this, R.layout.circle_views, null);
                                                ((CircleImageView) view.findViewById(R.id.cir_icon))
                                                        .setImageBitmap(resource);
                                                marker.setIcon(BitmapDescriptorFactory.fromView(view));
                                            }
                                        });
                            }



                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @OnClick(value = {R.id.backbt, R.id.order_bt,R.id.fabu_bt
    })
    public void OnMyClick(View view) {
        switch (view.getId()) {
            case R.id.fabu_bt:
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null||userList.size()==0){
                    Tools.redirectActivity(this,LoginActivity.class);
                    return;
                }
                Tools.redirectActivity(this,HelpingSubmitInfoActivity.class);
                break;
            case R.id.backbt:
                finish();
                break;

            case R.id.order_bt:
                List<User> oderuserList= Xutils.queryAll(getApplication(),User.class);
                if(oderuserList==null||oderuserList.size()==0){
            Tools.redirectActivity(this,LoginActivity.class);
                    return;
                }
               Tools.redirectActivity(this,HelpingOrderListActivity.class);
                break;

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }

    @Override
    public void onMyLocationChange(Location location) {
    }


    public void watchView(String helpid){
          Map<String,String> map=new HashMap<>();
          map.put("helpid",helpid);
        Xutils.POST(HttpUrl.userneedhelpaddviewscount, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
            if(aMapLocation==null){
                return;
            }
          city=aMapLocation.getCity();
          area=aMapLocation.getDistrict();
        if(isFirst==true){
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude()),21));
            isFirst=false;
            query();
        }
    }

}
